package cn.example.vip.mall.cart.service.impl;

import cn.example.vip.mall.cart.entity.Cart;
import cn.example.vip.mall.cart.mapper.CartMapper;
import cn.example.vip.mall.cart.service.CartService;
import cn.example.vip.mall.goods.entity.Sku;
import cn.example.vip.mall.goods.feign.SkuFeign;
import cn.example.vip.mall.util.RespResult;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {
	
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private SkuFeign skuFeign;
	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Override
	public List<Cart> list(String userName) {
		Cart cart = new Cart();
		cart.setUserName(userName);
		return cartMapper.findAll(Example.of(cart), Sort.by("_id"));
	}
	
	/**
	 * 查询购物车中, 用户选择的商品
	 * @param ids
	 * @return
	 */
	@Override
	public List<Cart> queryCartsByIds(List<String> ids) {
		if(ids != null && !ids.isEmpty()){
			Iterable<Cart> carts = cartMapper.findAllById(ids);
			return Lists.newArrayList(carts);
		}
		return null;
	}
	
	/**
	 * 商品加入购物车
	 * @param id
	 * @param userName
	 * @param num
	 * @return
	 */
	@Override
	public void add(String id, String userName, Integer num) {
		// ID 不能冲突
		// 1.删除当前商品的过往信息
		cartMapper.deleteById(userName + id);
		if(num >= 0) {
			// 2.根据 Id 查询Sku详情
			RespResult<Sku> respResult = skuFeign.querySkuById(id);
			System.out.println("------->check:" + respResult);
			Sku sku = respResult.getData();
			System.out.println("------->check:" + sku);
			// 3.将当前 Id 的商品加入购物车(存入MongoDB)
			Cart cart = new Cart(userName + id, userName, sku.getName(),
				sku.getPrice(), sku.getImage(), sku.getId(), num);
			System.out.println("------->check:" + cart);
			cartMapper.save(cart);
		}
	}
	
	/**
	 * 商品移出购物车
	 * @param ids
	 * @return
	 */
	@Override
	public void delete(List<String> ids) {
		mongoTemplate.remove(Query.query(Criteria.where("_id").in(ids)), Cart.class);
	}
}
